import fetch from 'node-fetch'
import qs from 'node:querystring'

export class ljsy extends plugin {
  constructor () {
    super({
      name: '灵界深渊',
      dsc: '灵界深渊自动化',
      route: '/ljsy',
      rule: [
        {
          method: 'get',
          path: '/signList',
          fnc: 'signList'
        },
        {
          method: 'get',
          path: '/sign',
          fnc: 'autoSign'
        },
        {
          method: 'get',
          path: '/signStatus',
          fnc: 'signStatus'
        }
      ]
    })
    // 定时任务
    this.task = [
      {
        cron: '1 0 * * *',
        name: '[灵界深渊][1] 自动签到，自动抽奖',
        fnc: () => this.autoSign()
      },
      {
        cron: '1 12 * * *',
        name: '[灵界深渊][2] 自动签到，自动抽奖',
        fnc: () => this.autoSign()
      }
    ]
    // 默认参数
    this.query_param = {
      ct: 'tagActivity',
      role_id: '457791974146097',
      game_id: 331,
      hd_id: 297
    }
  }

  async signStatus () {
    let status = await this.get('getSignStatus')

    this.send(status)
  }

  async signList () {
    let { type, page = 1, page_size=9999 } = this.params
    if (!type) {
      type = 3 // 签到历史
    } else {
      type = 2 // 祈愿历史
    }
    let history = await this.get(`getRecords&page=${page}&page_size=${page_size}&page_index=${type}`)

    this.send(history)
  }

  // 自动抽奖，自动抽奖
  async autoSign () {
    if (this.res) {
      this.send({ code: 1, msg: '正在执行签到，请稍后。。。' })
    }

    // 自动签到
    let isSign = await this.get('getTodaySignStatus')
    if (isSign.state) {
      if (isSign.data.is_sign) {
        isSign.msg = "今日已经签到了"
        this.log('info', '是否签到', isSign)
      } else {
        let doSign = await this.get('doSign')
        if (doSign.state) {
          this.log('info', '签到', doSign)
          // 领取累计签到奖励
          let getSignStatus = await this.get('getSignStatus')
          if (getSignStatus.state) {
            for (let i of getSignStatus.data.month) {
              if (getSignStatus.data.month_sign_count === i.day) {
                let getMonthSignReward = await this.get(`getMonthSignReward&days=${i.day}`)
                if (getMonthSignReward.state) {
                  this.log('info', '累计签到', getMonthSignReward)
                } else {
                  this.log('info', '累计签到', getMonthSignReward)
                }
              }
            }
          } else {
            this.log('info', '签到状态', getSignStatus)
          }
        } else {
          this.log('info', '签到', doSign)
        }
      }
    } else {
      this.log('info', '是否签到', isSign)
    }

    // 自动抽奖
    let count = 0
    let getTasks = await this.get('getTasks')
    if (getTasks.state) {
      for (let i of getTasks.data.tasks) {
        if (i.status !== 2) {
          let doTask = await this.get(`doTask&task_id=${i.id}`)
          if (doTask.state) {
            doTask.msg = "已完成任务"
            this.log('info', '完成任务', doTask)
            count += 1
          } else {
            this.log('info', '完成任务', doTask)
          }
          await this.sleep(500)
        }
      }
      let getRoleNum = await this.get('getRoleNum')
      if (count > 0 || (getRoleNum.state && getRoleNum.data.num)) {
        for (let i = 0; i < (count || getRoleNum.data.num); i++) {
          let pray = await this.get('pray')
          if (pray.state) {
            pray.msg = `获得 ${pray.data.content}`
            this.log('info', '祈愿', pray)
          } else {
            this.log('info', '祈愿', pray)
          }
          await this.sleep(500)
        }
      }
    } else {
      this.log('info', '祈愿任务', getTasks)
    }
    /*
    唤灵签到历史 https://sdk.sh9130.com/hd/?ac=getRecords&page=1&page_size=9999&page_index=3&page_index=2
    灵树祈愿剩余次数 https://sdk.sh9130.com/hd/?ac=getRoleNum
  灵树祈愿历史 https://sdk.sh9130.com/hd/?ac=getRecords&page=1&page_size=9999&page_index=2&page_index=2
    唤灵/灵树绑定 https://sdk.sh9130.com/hd/?ac=bindRole&open_id=oOYBd0gPqFzpozbpWLh4uEBpShus&union_id=oOYBd0gPqFzpozbpWLh4uEBpShus
    */
  }

  log (type, name, msg) {
    if (typeof msg === "object") {
      msg = [ msg.msg, msg ]
    } else {
      msg = [ msg ]
    }
    logger[type](`[灵界深渊][${this.query_param.role_id}][${name}]`, ...msg)
  }

  async get (ac) {
    let host = 'https://sdk.sh9130.com/hd/'
    // 处理url
    const url = ac => (host += `?ac=${ac}&` + qs.encode(this.query_param))
    let res = await fetch(url(ac))
    if (res.ok) {
      return await res.json()
    } else {
      return { state: 0, message: `${res.statusText} (${res.status})`, url: res.url }
    }
  }
}
